/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aptech.mBean;

import com.aptech.entities.TblManager;
import com.aptech.mBean.util.JsfUtil;
import com.aptech.mBean.util.PaginationHelper;
import com.aptech.sBean.TblManagerFacade;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author LanhAnh
 */
@ManagedBean(name = "managerController")
@SessionScoped
public class ManagerController implements Serializable {

    public static final String MANAGER_SESSION_KEY = "ManagerSession";
    @EJB
    private TblManagerFacade tblManagerFacade;
    private DataModel items = null;
    private PaginationHelper paginationHelper;
    private TblManager current;
    private int selectedItemIndex;
    private List<TblManager> listManagerByID;

    public List<TblManager> getListManagerByID(int mnID) {
        return tblManagerFacade.getManagerByID(mnID);
    }

    public TblManagerFacade getFacade() {
        return tblManagerFacade;
    }

    public TblManager getSelected() {
        if (current == null) {
            current = new TblManager();
            selectedItemIndex = -1;
        }
        return current;
    }

    public PaginationHelper getPaginationHelper() {
        if (paginationHelper == null) {
            paginationHelper = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return paginationHelper;
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPaginationHelper().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        paginationHelper = null;
    }

    public String prepareList() {
        recreateModel();
        return "ManagerManagement";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(tblManagerFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(tblManagerFacade.findAll(), true);
    }

    public SelectItem[] getItemsAvailableSelectOneStaffProject() {
        return JsfUtil.getSelectItems(tblManagerFacade.ViewStaffProject(2), true);
    }

    public String prepareCreate() {
        current = new TblManager();
        selectedItemIndex = -1;
        return "ManagerManagement";
    }

    public String create() {
        try {
            getFacade().create(current);
            return prepareCreate();
        } catch (Exception e) {
            return null;
        }
    }

//    public String checkLogin() {
//        try {
//            List<TblManager> list = getFacade().checkLogin(current.getMnUserName(), current.getMnPassword());
//            if (list.size() > 0) {
//                current = list.get(0);
//                JsfUtil.putSession(MANAGER_SESSION_KEY, current);
//                return "app-main";
////                if (current.getMnPermission() == 0) {
////                    JsfUtil.putSession(MANAGER_SESSION_KEY, current);
////                    return "admin";
////                } else if (current.getMnPermission() == 1) {
////                    JsfUtil.putSession(MANAGER_SESSION_KEY, current);
////                    return "order";
////                } else if (current.getMnPermission() == 2) {
////                    JsfUtil.putSession(MANAGER_SESSION_KEY, current);
////                    return "project";
////                }
//
//            }
//            // JsfUtil.addErrorMessage(ResourceBundle.getBundle("/i18n/Bundle").getString("LoginFail"));
//            return null;
//        } catch (Exception e) {
//            // JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/i18n/Bundle").getString("PersistenceErrorOccured"));
//            return null;
//        }
//
//    }
//    public String logout() {
//        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
//        if (session != null) {
//            session.invalidate();
//        }
//
//
//        FacesContext fc = javax.faces.context.FacesContext.getCurrentInstance();
//        ((HttpSession) fc.getExternalContext().getSession(false)).invalidate();
////        Application ap = getApplication();
////        NavigationHandler nh = ap.getNavigationHandler();
////        nh.handleNavigation(fc,null,"logout");
//        return "login";
//    }
    @FacesConverter(forClass = TblManager.class)
    public static class ManagerControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ManagerController controller = (ManagerController) context.getApplication().getELResolver().
                    getValue(context.getELContext(), null, "managerController");
            return controller.tblManagerFacade.find(getKey(value));
        }

        @Override
        public String getAsString(FacesContext context, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof TblManager) {
                TblManager o = (TblManager) object;
                return getStringKey(o.getMnID());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + TblManager.class.getName());
            }
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }
    }

    public void onEdit(RowEditEvent e) {
        FacesMessage msg = new FacesMessage("Edit User", ((TblManager) e.getObject()).getMnName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
        getFacade().edit((TblManager) e.getObject());
    }

    public void onEditCancel(RowEditEvent e) {
        FacesMessage msg = new FacesMessage("Edit Manager Cancelled", ((TblManager) e.getObject()).getMnName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    /**
     * Creates a new instance of ManagerController
     */
    public ManagerController() {
    }
}
